using LocalBoard.Domain;
using LocalBoard.Controller;

namespace LocalBoard.Web.UserControls
{
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;

	/// <summary>
	///		Summary description for UserInformation.
	/// </summary>
	public partial class UserInformation : System.Web.UI.UserControl
	{
		public const string MODE_REGISTER = "REGISTER";
		public const string MODE_CHANGE = "CHANGE";

		private string _mode = MODE_REGISTER;
		public string Mode
		{
			get {return _mode;}
			set {_mode = value;}
		}
		private bool _alreadyRegisteredUser;


		protected void Page_Load(object sender, System.EventArgs e)
		{
			if(Request.QueryString["updated"] != null && bool.Parse(Request.QueryString["updated"]))
				DisplayMessage("User information succesfully updated.");

			if(Request.IsAuthenticated)
			{
				Profile profile = ((ClubPrincipal)Context.User).UserProfile;
				userId.Text = profile.UserId;
				if(_mode.ToUpper() == MODE_REGISTER)
				{
					if(profile != null)
						_alreadyRegisteredUser = true;
				}
				if(_mode.ToUpper() == MODE_CHANGE)
					InitializeFields(profile);
				passwordRow.Visible = false;
				confirmPwdRow.Visible = false;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion

		#region Event handler
		protected void registerUser_Click(object sender, System.EventArgs e)
		{
//			if(!Request.IsAuthenticated && password.Text != confirmPassword.Text)
			if(!TwoPasswordsMatch())
				return;

			if(PhotoSubmitted() && !CheckUploadedFileSize())
					return;

			CreateUser(userId.Text, name.Text, password.Text, email.Text, UploadPhoto(), biography.Text);
			Security.RedirectToHome();
		}

		protected void changeUser_Click(object sender, System.EventArgs e)
		{
			if(!TwoPasswordsMatch())
				return;

			if(PhotoSubmitted() && !CheckUploadedFileSize())
				return;

			if(ChangeUser(userId.Text, name.Text, password.Text, email.Text, UploadPhoto(), biography.Text))
				Response.Redirect(ClubPage.AddQueryStringToUrl(Request.RawUrl, "updated", "true"));
		}
		#endregion

		#region Helper

		private void DisplayMessage(string text)
		{
			errorMessage.Text = text;
			errorMessage.Visible = true;
		}
		private void CreateUser(string userId, string name, string password, string email, string photoPath, string biography)
		{
			AdminController adminController = new AdminController(Global.AccessorFactory);
			adminController.CreateUser(new Profile(userId, name, password, email, photoPath, biography));
		}

		private void InitializeFields(Profile profile)
		{
			if(profile == null)
				return;
			//userId;
			name.Text = profile.UserName;
			biography.Text = profile.CustomInfo;
			email.Text = profile.Email;
			photo.ImageUrl = "~/" + profile.PhotoPath;
			photo.Visible = true;
			registerUser.Visible = false;
			changeUser.Visible = true;
			userIdValidator.Enabled = false;
			passwordValidator.Enabled = false;
		}

		private string UploadPhoto()
		{
			string photoPath = "";
			if(PhotoSubmitted())
				photoPath = new PhotoUploadController().WriteUploadedPhotoFile(photoUpload.PostedFile, userId.Text);
			return photoPath;
		}

		private bool PhotoSubmitted()
		{
			return photoUpload.Value != null && photoUpload.Value.Length > 0
				&& photoUpload.PostedFile != null;
		}

		private bool TwoPasswordsMatch()
		{
			if(password.Text != confirmPassword.Text)
			{
				DisplayMessage("Error: Password fields have to be matched.");
				return false;
			}
			return true;
		}
		#endregion

		private bool CheckUploadedFileSize()
		{
			if(photoUpload.PostedFile.ContentLength > 1024000)
			{
				errorMessage.Text = "File size is too big (Max 1MB).";
				errorMessage.Visible = true;
				return false;
			}
			return true;
		}

		private bool ChangeUser(string userId, string userName, string password, string email, string filePath, string customInfo)
		{
			AdminController adminController = new AdminController(Global.AccessorFactory);
			Profile profile = ((ClubPrincipal)Context.User).UserProfile;
			bool isDirty = false;
			if(profile.UserId != userId)
			{
				profile.UserId = userId;
				isDirty = true;
			}
			if(profile.UserName != userName)
			{
				profile.UserId = userId;
				isDirty = true;
			}
			if(profile.Password != password)
			{
				profile.Password = password;
				isDirty = true;
			}
			if(profile.Email != email)
			{
				profile.Email = email;
				isDirty = true;
			}
			if(filePath != null && filePath.Length > 0)
			{
				profile.PhotoPath = filePath;
				isDirty = true;
			}
			if(profile.CustomInfo != customInfo)
			{
				profile.CustomInfo = customInfo;
				isDirty = true;
			}

			if(isDirty)
			{
				adminController.UpdateUser(profile);
				return true;
			}
			else
				return false;
		}
	}
}
